package com.work.cos.util.thirdpay.weixinpay;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.work.cos.domain.vo.ComMemoryCacheContext;
import com.work.cos.util.constants.Constants;
import com.work.cos.util.thirdpay.weixinpay.config.WeixinConfig;
import com.work.cos.util.thirdpay.weixinpay.sign.MD5;
import com.work.cos.util.thirdpay.weixinpay.util.HttpUtil;
import com.work.cos.util.thirdpay.weixinpay.util.PayCommonUtil;
import com.work.cos.util.thirdpay.weixinpay.util.Util;
import com.work.cos.util.thirdpay.weixinpay.util.XMLUtil;

public class WeixinPay {
	static final Logger logger = LoggerFactory.getLogger(WeixinPay.class);

	public static Map<String, String> getWeixinPayInfo(String outTradeNo,
			String subject, String body, int price) {
		String notify_url="";
    	notify_url= WeixinConfig.notify_app_url;


		List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
		packageParams.add(new BasicNameValuePair("appid", WeixinConfig.app_id));
		packageParams.add(new BasicNameValuePair("body", body));
		packageParams.add(new BasicNameValuePair("mch_id", WeixinConfig.mch_id));
		packageParams.add(new BasicNameValuePair("nonce_str", Util.genNonceStr()));
		packageParams.add(new BasicNameValuePair("notify_url", ComMemoryCacheContext.getObjectFromMemory(Constants.URL_APP_ROOT) + notify_url));
		packageParams.add(new BasicNameValuePair("out_trade_no", outTradeNo));
		packageParams.add(new BasicNameValuePair("spbill_create_ip", "127.0.0.1"));
		packageParams.add(new BasicNameValuePair("total_fee", String.valueOf(price)));
		packageParams.add(new BasicNameValuePair("trade_type", "APP"));
        System.out.println(packageParams.toString());
		StringBuilder sb = new StringBuilder();

		for (int i = 0; i < packageParams.size(); i++) {
			sb.append(packageParams.get(i).getName());
			sb.append('=');
			sb.append(packageParams.get(i).getValue());
			sb.append('&');
		}
		sb.append("key=");
		sb.append(WeixinConfig.api_key);

		String packageSign;
		try {

			packageSign = MD5.getMessageDigest(sb.toString().getBytes("UTF-8"))
					.toUpperCase();
			packageParams.add(new BasicNameValuePair("sign", packageSign));

			StringBuilder uOrderParam = new StringBuilder();
			uOrderParam.append("<xml>");
			for (int i = 0; i < packageParams.size(); i++) {
				uOrderParam.append("<" + packageParams.get(i).getName() + ">");
				uOrderParam.append(packageParams.get(i).getValue());
				uOrderParam.append("</" + packageParams.get(i).getName() + ">");
				System.out.println(i+"value  ="+packageParams.get(i).getValue());

			}
			uOrderParam.append("</xml>");

			byte[] buf = Util.httpPost(WeixinConfig.UNIFIED_ORDER_URL,
					new String(uOrderParam.toString().getBytes("UTF-8"), "ISO-8859-1"));
			logger.info("buf =" +buf);
			String content = new String(buf);

			logger.debug("prepay resp={}", content);

			String prepay_id = null;
			Document document = DocumentHelper.parseText(content);
			 Element root = document.getRootElement();//根节点
			 Element d = root.element("prepay_id"); //如果没有content就报异常了
			 System.out.println(d+"  =d");
			if (d != null) {
				prepay_id = d.getText();
				Map<String, String> out = new HashMap<>();
				out.put("appid", WeixinConfig.app_id);
				out.put("noncestr", Util.genNonceStr());
				out.put("package", "Sign=WXPay");
				out.put("partnerid", WeixinConfig.mch_id);
				out.put("prepayid", prepay_id);
				out.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));

				StringBuilder sb2 = new StringBuilder();
				sb2.append("appid").append('=').append(out.get("appid")).append('&');
				sb2.append("noncestr").append('=').append(out.get("noncestr")).append('&');
				sb2.append("package").append('=').append(out.get("package")).append('&');
				sb2.append("partnerid").append('=').append(out.get("partnerid")).append('&');
				sb2.append("prepayid").append('=').append(out.get("prepayid")).append('&');
				sb2.append("timestamp").append('=').append(out.get("timestamp")).append('&');
				sb2.append("key=");
				sb2.append(WeixinConfig.api_key);
				out.put("sign", MD5.getMessageDigest(sb2.toString().getBytes()).toUpperCase());

				return out;
			} else {
				System.out.println("这个异常");
				logger.error("unexpected xml conetnt:\n{}", content);
			}
		} catch (DocumentException e) {
			logger.error("xml format", e);
		} catch (UnsupportedEncodingException e) {
			logger.error("encoding problem.", e);
		}
		System.out.println("这个返回没有");
		return null;
	}

    public String weixin_pay(String outTradeNo, String body, int price) throws Exception {
        // 账号信息
//        String appid = PayConfigUtil.APP_ID;  // appid
        //String appsecret = PayConfigUtil.APP_SECRET; // appsecret
//        String mch_id = PayConfigUtil.MCH_ID; // 商业号
        String key = WeixinConfig.API_KEY; // key

        String currTime = PayCommonUtil.getCurrTime();
        String strTime = currTime.substring(8, currTime.length());
        String strRandom = PayCommonUtil.buildRandom(4) + "";
        String nonce_str = strTime + strRandom;

        String order_price = String.valueOf(price); // 价格   注意：价格的单位是分
        String out_trade_no = outTradeNo; // 订单号

        // 获取发起电脑 ip
//        String spbill_create_ip = PayConfigUtil.CREATE_IP;
        // 回调接口
//        String notify_url = PayConfigUtil.NOTIFY_URL;
        String trade_type = "NATIVE";

        SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
        packageParams.put("appid", WeixinConfig.APP_ID);
        packageParams.put("mch_id", WeixinConfig.MCH_ID);
        packageParams.put("nonce_str", nonce_str);
        packageParams.put("body", body);
        packageParams.put("out_trade_no", out_trade_no);
        packageParams.put("total_fee", order_price);
        packageParams.put("spbill_create_ip", "127.0.0.1");
        packageParams.put("notify_url", ComMemoryCacheContext.getObjectFromMemory(Constants.URL_APP_ROOT) + WeixinConfig.notify_url);
        packageParams.put("trade_type", "NATIVE");

        String sign = PayCommonUtil.createSign("UTF-8", packageParams,key);
        packageParams.put("sign", sign);

        String requestXML = PayCommonUtil.getRequestXml(packageParams);
        System.out.println(requestXML);

        String resXml = HttpUtil.postData(WeixinConfig.UNIFIED_ORDER_URL, requestXML);



//        weixin_notify(request, response);

        Map map = XMLUtil.doXMLParse(resXml);
        //String return_code = (String) map.get("return_code");
        //String prepay_id = (String) map.get("prepay_id");
        String urlCode = (String) map.get("code_url");

        return urlCode;
}

//    public static String QRfromGoogle(String chl) throws Exception {
//        int widhtHeight = 300;
//        String EC_level = "L";
//        int margin = 0;
//        chl = UrlEncode(chl);
//
//        String QRfromGoogle ="weixin：//wxpay/bizpayurl?sign=XXXXX&appid=XXXXX&mch_id=XXXXX&product_id=XXXXXX&time_stamp=XXXXXX&nonce_str=XXXXX";
//
//        return QRfromGoogle;
//    }

    // 特殊字符处理
    public static String UrlEncode(String src)  throws UnsupportedEncodingException {
        return URLEncoder.encode(src, "UTF-8").replace("+", "%20");
    }






}
